﻿using MediatR;
using PublicCommon;
using T_vehicle.Domain;
using T_vehicle.Infrastructure.Interfacec;
using T_vehicle.Read.API.Application.Command.RepairRecordsCommand;

namespace T_vehicle.Read.API.Application.CommandHandlers.RepairRecordsCommandHandlers
{
    public class GetRepairRecordsCommandHandlers:IRequestHandler<GetRepairRecordsCommand, PageResult<RepairRecords>>
    {
        private readonly IRepairRepository repairRepository;

        public GetRepairRecordsCommandHandlers(IRepairRepository repairRepository)
        {
            this.repairRepository = repairRepository;
        }

        public async Task<PageResult<RepairRecords>> Handle(GetRepairRecordsCommand request, CancellationToken cancellationToken)
        {
            var list = repairRepository.GetAllAsync().Result.Where(x => x.IsDel == false).AsQueryable();

            if (!string.IsNullOrEmpty(request.Head))
            {
                list = list.Where(x => x.Head.Contains(request.Head));
            }
        
            if (!string.IsNullOrEmpty(Convert.ToString(request.MaintenanceDate)))
            {
                list = list.Where(x => x.MaintenanceDate == request.MaintenanceDate);
            }

            if (!string.IsNullOrEmpty(request.LicenNumbers))
            {
                list = list.Where(x => x.LicenNumbers.Contains(request.LicenNumbers));
            }

            int totalCount = list.Count();
            int pageCount = (int)Math.Ceiling((totalCount * 1.0) / request.pageSize);
            var res = list.Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();
            return  new PageResult<RepairRecords>
            {
                PageCount = pageCount,
                TotalCount = totalCount,
                List = res
            };
        }
    }
}
